path = require 'path'
fs = require 'fs'
Promise = require 'bluebird'
co = require 'co'

pReadFile = Promise.promisify fs.readFile

EntityService = require '../service/EntityService'
TrackService = require '../service/TrackService'
PromotionService = require '../service/PromotionService'

config = require '../config'
log = require '../log'

pageDir = "promotion"

pageCache = {}

exports.toPromotion = ->
    promotionName = @params.name
    userIp = @ips?.length && @ips[@ips.length - 1] || @ip
    channel = @query._c
    userAgent = @request.get 'user-agent'
    uid = @cookies.get('c', {signed: true, httpOnly: false}) # 用户唯一标识

    log.logs?.promotion?.info 'access', {promotionName, userIp, channel, uid, userAgent}

    promotion = yield from EntityService.gFindOneByCriteria({}, null, 'F_Promotion', {name: promotionName})

    unless promotion
        @status = 404
        @render 'promotion404'
        return

    now = new Date()

    if @query._nocookie
        PromotionService.recordNoCookieView promotionName, channel, userIp, userAgent, now
        @type = '.js'
        @body = ''
    else
        if not uid
            uid = TrackService.newUser({_createdOn: now, userIp})
            @cookies.set 'c', uid, {signed: true, httpOnly: false}

        PromotionService.record promotionName, channel, uid, userIp, userAgent, now

        @body = yield from gGetPage promotion.pagePath

exports.gInvalidateStaticPageCache = ->
    pageCache = {}
    @status = 204
    yield return

exports.gPersistPageViewNow = ->
    yield from PromotionService.gPersist()
    @status = 204

exports.gReport = ->
    log.system.info 'to report'
    r = yield from PromotionService.gBuildReport(@params.promotion)
    @body = r

exports.gGetPromotionChannels = ->
    promotionName = @params.promotion
    promotion = yield from EntityService.gFindOneByCriteria({}, null, 'F_Promotion', {name: promotionName})

    unless promotion
        @status = 404
        return

    r = yield from PromotionService.gGetPromotionChannels(promotionName)
    @body = r || {}

exports.gPutPromotionChannels = ->
    promotionName = @params.promotion
    promotion = yield from EntityService.gFindOneByCriteria({}, null, 'F_Promotion', {name: promotionName})

    unless promotion
        @status = 404
        return

    yield from PromotionService.gPutPromotionChannels(promotionName, @request.body)

    @status = 204

gGetPage = (pagePath)->
    page = pageCache[pagePath]
    return page if page

    pageFullPath = path.join config.fileDir, pageDir, pagePath

    page = yield pReadFile pageFullPath, 'utf8'

    pageCache[pagePath] = page
    page




